package com.ocom.accesservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ocom.accesservice.dao.IDaoAreaInfo;
import com.ocom.accesservice.service.*;
import com.ocom.common.dto.AreaDto;
import com.ocom.common.entity.access.EntityMjAreaInfo;
import com.ocom.common.entity.access.EntityMjDeviceInfo;
import com.ocom.common.entity.access.EntityMjGroupPer;
import com.ocom.common.entity.access.EntityMjRegionInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.AreaInfoVo;
import com.ocom.common.vo.AreaVo;
import com.ocom.common.vo.DelAreaVo;
import com.ocom.common.vo.MachineListVo;
import com.ocom.common.vo.accessdevice.RegionAreaInfo;
import com.ocom.mysql.aspect.DataSourceAspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class AreaInfoServiceImpl  extends ServiceImpl<IDaoAreaInfo, EntityMjAreaInfo> implements AreaInfoService {

    //注入持久层
    @Autowired
    private IDaoAreaInfo daoAreaInfo;

    @Autowired
    GroupPerService groupPerService;

    @Autowired
    DeviceInfoService deviceInfoService;

    @Autowired
    MjDeviceInfoService mjDeviceInfoService;

    @Autowired
    MjRegionInfoService mjRegionInfoService;

    //1、从门禁区域表mj_area_info查出所有com_id=companyID的areaNo(areaName)
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "comId")
    @Override
    public List<EntityMjAreaInfo> GetAreaName(AreaVo areaVo, Long comId) {
        QueryWrapper<EntityMjAreaInfo> query = Wrappers.query();
        if (StringUtils.isNotNull(areaVo.getComId())){
            query.eq("com_id",areaVo.getComId());
        }
        if (StringUtils.isNotNull(areaVo.getRegionId())){
            query.eq("region_id",areaVo.getRegionId());
        }
        if (StringUtils.isNotNull(areaVo.getAreaName())){
            query.like("area_name",areaVo.getAreaName());
        }
        PageHelper.startPage(areaVo.getPage(), areaVo.getSize());

        return this.list(query);
    }
    /**
     * 添加区域
     * */
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "comId")
    @Transactional
    @Override
    public EntityMjAreaInfo NewArea(AreaDto areaDto,Long comId) {
        // 检查mj_area_info表，在同一个单位区域名称是否已存在，存在返回错误；
        EntityMjAreaInfo info = new EntityMjAreaInfo();
        QueryWrapper<EntityMjAreaInfo> mjAreaInfoQueryWrapper = Wrappers.query();
        if (StringUtils.isNotNull(areaDto.getComId())){
            mjAreaInfoQueryWrapper.eq("com_id",areaDto.getComId());
            info.setComId(areaDto.getComId());
        }
        if (StringUtils.isNotNull(areaDto.getRegionId())){
            mjAreaInfoQueryWrapper.eq("region_id",areaDto.getRegionId());
            info.setRegionId(areaDto.getRegionId());
        }
        if (StringUtils.isNotNull(areaDto.getAreaName())){
            mjAreaInfoQueryWrapper.eq("area_name",areaDto.getAreaName());
            info.setAreaName(areaDto.getAreaName());
        }
        info.setIndoorState(areaDto.getIndoorState());
        info.setOutdoorState(areaDto.getOutdoorState());
        daoAreaInfo.insert(info);
        return info;
    }
    /**
     * 修改区域名称
     * */
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER,companyId = "comId")
    @Transactional
    @Override
    public String UpdateAreaName(AreaDto areaDto,Long comId) {

        // 检查mj_area_info表，在同一个单位区域名称是否已存在，存在返回错误；
        EntityMjAreaInfo info = new EntityMjAreaInfo();
        UpdateWrapper<EntityMjAreaInfo> mjAreaInfoQueryWrapper = new UpdateWrapper<>();
        if (StringUtils.isNotNull(areaDto.getComId())){
            mjAreaInfoQueryWrapper.eq("com_id",areaDto.getComId());
        }
        if (StringUtils.isNotNull(areaDto.getRegionId())){
            mjAreaInfoQueryWrapper.set("region_id",areaDto.getRegionId());
        }
        if (StringUtils.isNotNull(areaDto.getAreaId())){
            mjAreaInfoQueryWrapper.eq("area_id",areaDto.getAreaId());
        }
        mjAreaInfoQueryWrapper.set("area_name",areaDto.getAreaName());
        mjAreaInfoQueryWrapper.set("indoor_state",areaDto.getIndoorState());
        mjAreaInfoQueryWrapper.set("outdoor_state",areaDto.getOutdoorState());

        if (StringUtils.isNotNull(areaDto.getUserName())){
            mjAreaInfoQueryWrapper.set("user_name", areaDto.getUserName());
        }
        this.update(mjAreaInfoQueryWrapper);
        return info.getAreaName();
    }

    /**
     * 校验区域名称是否唯一
     *
     * @param AreaName 单位区域名称
     * @return 结果
     */
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "comId")
    @Override
    public EntityMjAreaInfo checkAreaNameUnique(Long comId, String AreaName) {
        QueryWrapper<EntityMjAreaInfo> query = Wrappers.query();
        if (StringUtils.isNotNull(comId)){
            query.eq("com_id",comId);
        }
        query.eq("area_name",AreaName).last("limit 1");
        //校验
        return daoAreaInfo.selectOne(query);
    }

    /**
     * 移除区域
     * */
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER,companyId = "companyID")
    @Transactional
    @Override
    public void RemoveArea(DelAreaVo delAreaVo, Long companyID) {
        QueryWrapper<EntityMjAreaInfo> query = Wrappers.query();
        if (StringUtils.isNotNull(delAreaVo.getComId())){
            query.eq("com_id",delAreaVo.getComId());
        }
        if (StringUtils.isNotNull(delAreaVo.getAreaId())){
            query.eq("area_id",delAreaVo.getAreaId());
        }
        daoAreaInfo.delete(query);

    }

    /**
     * 获取区域名称
     *
     * @return*/
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "comId")
    @Override
    public EntityMjAreaInfo getAreaById(Long areaId,Long comId) {
        return daoAreaInfo.selectById(areaId);
    }


    @DataSourceAspect(type= DataSourceEnum.PART_DB)
    @Override
    public EntityMjAreaInfo getAreaInfoById(Long companyId, Long areaId) {
        QueryWrapper<EntityMjAreaInfo> query = Wrappers.query();
        if (StringUtils.isNotNull(companyId)){
            query.eq("com_id",companyId);
        }
        if (StringUtils.isNotNull(areaId)){
            query.eq("area_id",areaId);
        }
        query.last("limit 1");
        return daoAreaInfo.selectOne(query);
    }

    @DataSourceAspect(type= DataSourceEnum.PART_DB)
    @Override
    public List<EntityMjAreaInfo> getAreaListByCompanyId(Long companyId) {
        QueryWrapper<EntityMjAreaInfo> query = Wrappers.query();
        query.eq("com_id",companyId);
        return this.list(query);
    }

    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER)
    @Transactional
    @Override
    public EntityMjAreaInfo newArea(Long companyId, Long regionId, String areaName, Long pId) {
        EntityMjAreaInfo mjAreaInfo=new EntityMjAreaInfo();
        mjAreaInfo.setAreaName(areaName);
        mjAreaInfo.setComId(companyId);
        mjAreaInfo.setRegionId(regionId);
        this.save(mjAreaInfo);
        return mjAreaInfo;
    }

    /**获取区域信息
     * @return*/
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "comId")
    @Override
    public List<EntityMjAreaInfo> GetAreaInfo(Long comId,Integer regionId, Integer areaId, String areaName) {
        QueryWrapper<EntityMjAreaInfo> query = Wrappers.query();
        if (StringUtils.isNotNull(comId)){
            query.eq("com_id",comId);
        }
        if (regionId !=null && regionId!=-1){
            query.eq("region_id",regionId);
        }
        if (areaId !=null && areaId!=-1){
            query.eq("area_id",areaId);
        }
        if (StringUtils.isNotEmpty(areaName)){
            query.like("area_name",areaName);
        }
        return daoAreaInfo.selectList(query);
    }




    @DataSourceAspect(type= DataSourceEnum.PART_DB)
    @Override
    public List<AreaInfoVo> getAreaList(Long companyId) {
        QueryWrapper<EntityMjAreaInfo> queryWrapper=new QueryWrapper<>();
      
        queryWrapper.eq("com_id",companyId);
        List<EntityMjAreaInfo> list= this.list(queryWrapper);

        List<AreaInfoVo> list1=new ArrayList<>();
        for (EntityMjAreaInfo entityMjAreaInfo:list) {
            AreaInfoVo areaInfoVo= new AreaInfoVo();
            areaInfoVo.setAreaNo(entityMjAreaInfo.getAreaId());
            areaInfoVo.setAreaName(entityMjAreaInfo.getAreaName());

            QueryWrapper<EntityMjGroupPer> entityMjGroupPerQueryWrapper=new QueryWrapper<>();
            entityMjGroupPerQueryWrapper.eq("area_id",entityMjAreaInfo.getAreaId());
            areaInfoVo.setUserNumber(groupPerService.count(entityMjGroupPerQueryWrapper));

            QueryWrapper<EntityMjDeviceInfo> entityMjDeviceInfoQueryWrapper=new QueryWrapper<>();
            entityMjDeviceInfoQueryWrapper.eq("area_id",entityMjAreaInfo.getAreaId());
            areaInfoVo.setMachineNumber(deviceInfoService.count(entityMjDeviceInfoQueryWrapper));

            List<EntityMjDeviceInfo> list2 =deviceInfoService.list(entityMjDeviceInfoQueryWrapper);

            List<MachineListVo> machineListVoList=new ArrayList<>();

            if(list2.size()>0){
                for (EntityMjDeviceInfo entityMjDeviceInfo: list2){
                    MachineListVo machineListVo=new MachineListVo();
                    machineListVo.setMachId(entityMjDeviceInfo.getDeviceId());
                    machineListVo.setMachName(entityMjDeviceInfo.getDeviceName());
                    machineListVo.setExNumber(entityMjDeviceInfo.getDeviceNo());
                    machineListVoList.add(machineListVo);
                }
            }
            areaInfoVo.setMachineList(machineListVoList);

            list1.add(areaInfoVo);
        }

        return  list1;
    }


    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB)
    public RegionAreaInfo getAreaInfoByMachNo(Long companyId,String machNo) {
        EntityMjDeviceInfo entityMjDeviceInfo=mjDeviceInfoService.getMachineInfoByMachNo(companyId,machNo);
        if(entityMjDeviceInfo==null || entityMjDeviceInfo.getAreaId()==0l){
            return new RegionAreaInfo();
        }
        QueryWrapper<EntityMjAreaInfo> queryWrapper=new QueryWrapper();
        queryWrapper.eq("com_id",companyId);
        queryWrapper.eq("area_id",entityMjDeviceInfo.getAreaId());
        queryWrapper.last("limit 1");
        EntityMjAreaInfo entityMjAreaInfo=this.getOne(queryWrapper);
        if(entityMjAreaInfo==null){
            return new RegionAreaInfo();
        }
        RegionAreaInfo regionAreaInfo = new RegionAreaInfo();
        regionAreaInfo.setAreaId(entityMjAreaInfo.getAreaId().intValue());
        regionAreaInfo.setAreaName(entityMjAreaInfo.getAreaName());
        regionAreaInfo.setOutdoorState(entityMjAreaInfo.getOutdoorState());
        regionAreaInfo.setIndoorState(entityMjAreaInfo.getIndoorState());
        if(entityMjAreaInfo.getRegionId()==0l){
            return regionAreaInfo;
        }

        QueryWrapper<EntityMjRegionInfo> entityMjRegionInfoQueryWrapper=new QueryWrapper<>();
        entityMjRegionInfoQueryWrapper.last("limit 1");
        entityMjRegionInfoQueryWrapper.eq("region_id",entityMjAreaInfo.getRegionId());
        entityMjRegionInfoQueryWrapper.eq("com_id",companyId);
        EntityMjRegionInfo entityMjRegionInfo=mjRegionInfoService.getOne(entityMjRegionInfoQueryWrapper);
        if(entityMjRegionInfo==null){
            return regionAreaInfo;
        }
        regionAreaInfo.setRegionId(entityMjRegionInfo.getRegionId().intValue());
        regionAreaInfo.setRegionName(entityMjRegionInfo.getRegionName());
        return regionAreaInfo;
    }

    /**
     * 区域权限列表 （getAreaGroupList）
     *
     * @return*/
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "comId",isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<EntityMjAreaInfo> GetAreaGroupList(Long comId, Long areaId, String range) {
        QueryWrapper<EntityMjAreaInfo> query = Wrappers.query();
        query.eq("com_Id",comId);
        if (StringUtils.isNotNull(areaId)){
            query.eq("area_id",areaId);
        }
        if (StringUtils.isNotEmpty(range)){
            query.in("area_id",range);
        }

        return daoAreaInfo.selectList(query);
    }

}
